<template>
  <article class="ad-text-slider">
    <div class="text-wrap">
      <div class="text-group" ref="textGroup">
        <h2 v-for="(item, index) in texts" :key="index">{{ item }}</h2>
      </div>
    </div>
    <div class="bullets">
      <span v-for="item in texts.length" :key="item" @click="moveSlider(item)" :class="{ active: textIndex == item }"></span>
    </div>
  </article>
</template>
<script lang="ts" setup>
const props = defineProps<{
  texts: string[]
}>()
const emits = defineEmits<{
  (e: "getIndex", i: number): void
}>()
const textIndex = ref(1)
const textGroup = ref<HTMLElement | null>(null)
// 文字轮播
const moveSlider = (index: number) => {
  // 当用户点击时暂时清除定时轮播
  clearInterval(regularTime)
  textIndex.value = index
  emits("getIndex", index)
  nextTick(() => {
    textGroup.value!.style.transform = `translateY(${-(index - 1) * 2.2}rem)`
  })
  // 用户无操作5s后开始定时轮播
  setTimeout(() => {
    regularMove()
  }, 5000)
}
let regularTime: any = 0
// 开始定时轮播
const regularMove = () => {
  clearInterval(regularTime)
  regularTime = setInterval(() => {
    textIndex.value++
    if (textIndex.value == props.texts.length + 1) {
      textIndex.value = 1
    }
    emits("getIndex", textIndex.value)
    nextTick(() => {
      textGroup.value!.style.transform = `translateY(${-(textIndex.value - 1) * 2.2}rem)`
    })
  }, 2000)
}
onMounted(() => {
  regularMove()
})
</script>
<style lang="scss" scoped>
.ad-text-slider {
  @include flex;
  justify-content: center;
  flex-direction: column;
  .text-wrap {
    max-height: 2.2rem;
    overflow: hidden;
    margin-bottom: 2.5rem;
    transition: 0.5s;
    .text-group {
      display: flex;
      flex-direction: column;
      text-align: center;
      transform: translateY(0);
      transition: 0.5s;
      h2 {
        line-height: 2.2rem;
        font-weight: 600;
        font-size: 1.6rem;
        transition: 0.5s;
      }
    }
  }

  .bullets {
    @include flex;
    justify-content: center;
    span {
      display: block;
      width: 0.5rem;
      height: 0.5rem;
      background-color: #aaa;
      margin: 0 0.25rem;
      border-radius: 50%;
      cursor: pointer;
      transition: 0.3s;
    }
    .active {
      width: 1.1rem;
      background-color: #151111;
      border-radius: 1rem;
    }
  }
}
@media (max-width: 530px) {
  .text-slider {
    .text-wrap {
      margin-bottom: 1rem;
      .text-group {
        h2 {
          font-size: 1.2rem;
        }
      }
    }
  }
}
</style>
